package com.jsy.learnnetty.echo;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;

/**
 * @author: SongyangJi
 * @description:
 * @since: 2021/10/13
 */
public class ClientEnd {

    private String clientName;

    private final String address;

    private final int port;

    private Channel channel;


    public ClientEnd(String address, int port) {
        this.address = address;
        this.port = port;
        start();
    }

    public void start() {
        EchoClientHandler echoClientHandler = new EchoClientHandler();

        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventExecutors)
                .channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(address, port))
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(echoClientHandler);
                    }
                });
        try {
            ChannelFuture future = bootstrap.connect().sync();
            System.out.println("connect server successfully...");
            this.channel = echoClientHandler.getChannel();

            work();

            future.channel().closeFuture().sync();
            System.out.println("client channel close...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                eventExecutors.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void work() {
        Scanner reader = new Scanner(System.in);
        System.out.println("input your name...");
        this.clientName = reader.nextLine();

        System.out.println("now you can send messages to server");
        String msg;
        while ((msg = reader.nextLine()) != null) {
            if (msg.length() == 0) continue;
            if (msg.equals("end")) {
                System.out.println("try to end connect");
                this.channel.writeAndFlush(Unpooled.copiedBuffer("end", StandardCharsets.UTF_8));
                break;
            }
            this.sendMessage(msg);
        }
    }

    private void sendMessage(String msg) {
        this.channel.writeAndFlush(Unpooled.copiedBuffer(clientName + " says " + msg, StandardCharsets.UTF_8));
    }


    public static void main(String[] args) {
        new ClientEnd("localhost", 7777);
    }
}
